package com.wawei.seeds;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.wawei.seeds.model.ExpertInfo;
import com.wawei.seeds.model.HeroInfo;
import com.wawei.seeds.services.WalnutExpertServiceHandler;
import com.wawei.seeds.services.WalnutRegAuthServiceHandler;
import com.wawei.seeds.utils.PrefUtils;
import com.wawei.seeds.utils.RetrofitNetworkService;
import com.wawei.seeds.utils.WalnutBaseNofityHandler;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit.RestAdapter;

/**
 *
 * Created by t27891 on 15/7/5.
 */
public class WalnutLoginActivity extends ActionBarActivity {
    @InjectView(R.id.walnut_event_sharing)View sharingView;
    @InjectView(R.id.walnut_logo)View backView;
    @InjectView(R.id.walnut_login_staffno)EditText staffnoMobileView;
    @InjectView(R.id.walnut_login_password)EditText passwordView;
    @InjectView(R.id.walnut_login_submit)View loginBtn;
    @InjectView(R.id.progressBar)ProgressBar progressBar;
    @InjectView(R.id.walnut_login_reg)View regNewView;
    @InjectView(R.id.walnut_login_reset)View resetPasswordView;

    private static final int USER_LOGIN = 0;
    private static final int CHECK_EXPERT = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_walnut_login);
        ButterKnife.inject(this);
        init();
    }

    private void init(){
        sharingView.setVisibility(View.GONE);
        staffnoMobileView.setText(PrefUtils.getPrefUser(this));

        backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                finish();
            }
        });
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
        regNewView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });
        resetPasswordView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetPassword();
            }
        });
    }

    private void login(){
        String staffnoMobile = staffnoMobileView.getText().toString();
        String password = passwordView.getText().toString();
        if(null == staffnoMobile || staffnoMobile.trim().length() == 0){
            Toast.makeText(this, getResources().getText(R.string.input_staffno_mobile), Toast.LENGTH_SHORT).show();
            staffnoMobileView.setFocusable(true);
            return;
        }
        if(null == password || password.trim().length() == 0){
            Toast.makeText(this, getResources().getText(R.string.input_password), Toast.LENGTH_SHORT).show();
            passwordView.setFocusable(true);
            return;
        }

        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        WalnutRegAuthServiceHandler serviceHandler = new WalnutRegAuthServiceHandler();
        LoginNotifyHandler notifyHandler = new LoginNotifyHandler(this);

        HeroInfo heroInfo = new HeroInfo();
        heroInfo.userName = staffnoMobile;
        heroInfo.password = password;

        Bundle bundle = new Bundle();
        bundle.putSerializable(SeedsApp.LOGIN_USER, heroInfo);
        bundle.putString(SeedsApp.CLIENT_ID, PushManager.getInstance().getClientid(this));

        serviceHandler.login(restAdapter, bundle, notifyHandler, USER_LOGIN);
        progressBar.setVisibility(View.VISIBLE);
    }

    private void register(){
        Intent regIntent = new Intent(this, WalnutRegistrationActivity.class);
        startActivity(regIntent);
        finish();
    }

    private void resetPassword() {
        Intent intent = new Intent(this, WalnutResetPasswordActivity.class);
        startActivity(intent);
    }

    private void isExpert(String expertId){
        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        LoginNotifyHandler nofityHandler = new LoginNotifyHandler(this);

        WalnutExpertServiceHandler expertServiceHandler = new WalnutExpertServiceHandler(this);
        expertServiceHandler.checkExpert(restAdapter, expertId, nofityHandler, CHECK_EXPERT);
    }

    private static class LoginNotifyHandler extends WalnutBaseNofityHandler<WalnutLoginActivity, HeroInfo>{
        public LoginNotifyHandler(WalnutLoginActivity walnutLoginActivity) {
            super(walnutLoginActivity);
        }

        @Override
        public void handleOtherMessage(Message msg) {
            get().progressBar.setVisibility(View.GONE);
            Bundle bundle = msg.getData();
            if(null == bundle.getString(RetrofitNetworkService.RESULT_ERROR)){
                Toast.makeText(get(), R.string.walnut_deal_timeout, Toast.LENGTH_SHORT).show();
                return;
            }
            if(!bundle.getString(RetrofitNetworkService.RESULT_ERROR).equals(RetrofitNetworkService.RESULT_ERROR_NONE)){
                Toast.makeText(get(), R.string.walnut_login_error, Toast.LENGTH_SHORT).show();
                return;
            }
            if(msg.what == USER_LOGIN){
                get().progressBar.setVisibility(View.GONE);
                HeroInfo heroInfo = (HeroInfo)msg.getData().getSerializable(RetrofitNetworkService.RESULT_DATA);


                SeedsApp app = (SeedsApp) get().getApplication();
                app.getSession().put(SeedsApp.LOGIN_USER, heroInfo);
                PrefUtils.markUserPassword(get(), heroInfo.userName, heroInfo.password);
                PrefUtils.markUserId(get(), Integer.valueOf(heroInfo.userId));
                PrefUtils.markUserProfileImgUri(get(), heroInfo.headPortrait);

                get().isExpert(heroInfo.userId);

                Intent mainIntent = new Intent(get(), WalnutMainActivity.class);
                get().startActivity(mainIntent);
                get().finish();
            }
            else if(msg.what == CHECK_EXPERT){
                ExpertInfo expertInfo = (ExpertInfo)msg.getData().getSerializable(RetrofitNetworkService.RESULT_DATA);

                SeedsApp app = (SeedsApp) get().getApplication();
                if(null != expertInfo){
                    app.getSession().put(SeedsApp.IS_EXPERT, "yes");
                }
                else {
                    app.getSession().put(SeedsApp.IS_EXPERT, "no");
                }
            }
        }
    }
}
